package com.example.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

import com.example.agenda.CadastroActivity;
import com.example.agenda.R;
import com.example.util.StaticUtil;
import com.example.vo.ContactDetails;

public class ListaAdapter extends BaseAdapter {

	private Context mContext;
	private LayoutInflater mInflater;
	private List<ContactDetails> mContactDetails;
	private List<String> mDeletedContacts;

	public ListaAdapter(Context ctx, List<ContactDetails> contactDetailsArray) {
		this.mContext = ctx;
		this.mContactDetails = contactDetailsArray;
		this.mInflater = LayoutInflater.from(ctx);
		this.mDeletedContacts = new ArrayList<String>();
	}

	@Override
	public int getCount() {
		return this.mContactDetails.size();
	}

	@Override
	public ContactDetails getItem(int position) {
		if (mContactDetails.get(position) != null) {
			return mContactDetails.get(position);
		} else {
			return null;
		}
	}

	@Override
	public long getItemId(int position) {
		if (mContactDetails.get(position) != null) {
			return Long.valueOf(mContactDetails.get(position).getId());
		} else {
			return 0;
		}
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		View view = convertView;
		view = mInflater.inflate(R.layout.item_lista, null);

		TextView txtView = (TextView) view.findViewById(R.id.txtView);
		txtView.setText(mContactDetails.get(position).getDisplayName());
		txtView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ContactDetails contactDetails = (ContactDetails) mContactDetails
						.get(position);

				Intent intent = new Intent(mContext, CadastroActivity.class);
				intent.putExtra(StaticUtil.ID, contactDetails.getId());
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_SINGLE_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);

				mContext.startActivity(intent);
			}

		});

		CheckBox checkBox = (CheckBox) view.findViewById(R.id.chkBox);
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					mDeletedContacts.add(mContactDetails.get(position).getId());
				} else {
					mDeletedContacts.remove(mContactDetails.get(position).getId());
				}
			}
		});

		return view;
	}

	public List<String> getSelectItens() {
		return mDeletedContacts;
	}
}
